<template>
  <div>
    <img src="../../assets/aaa.png" style="width: 125px; height: 125px; position: absolute; top: 40px; left: 280px;">
    <div class="title">
      <h1>原神，启动！</h1>
    </div>

    <el-card shadow="hover" style="margin-left: 900px; width: 125px">
      <div style="font-size: 10px;margin-left: 10px;margin-top:-5px ;color: #0d8d84;cursor: pointer">{{ currentDate }}</div>
      <div
          style="width: 90px; height: 90px; line-height: 90px; border-radius: 50%; background-color: #1E90FF;
        font-size: 25px; color: #fff; text-align: center; cursor: pointer; box-shadow: 0 0 30px rgba(0, 0, 0, .2);"
          type="button"
          @click="sign"
      >
        打卡
      </div>
      <div v-if="location" style="margin-top: 8px; font-size: 10px;">
        <div>{{ location.province }}{{ location.city }}</div>
      </div>
    </el-card>


    <!-- 条件选择 -->
    <el-row class="selects">
      <div class="flex flex-wrap gap-4 items-center">
        <!-- 输入框 -->
        <el-input v-model="fullName" style="width: 240px;height: 33px" placeholder="请输入关键字"/>
        <!-- 类型 -->
        <el-select v-model="type" placeholder="类型" style="width: 240px">
          <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"/>
        </el-select>
        <!-- 日期选择器 -->
        <el-date-picker
            v-model="repairTime"
            type="datetimerange"
            start-placeholder="开始时间"
            end-placeholder="截止时间"
            format="YYYY-MM-DD HH:mm:ss"
            date-format="YYYY/MM/DD ddd"
            time-format="A hh:mm:ss"
        />
        <!-- 查询按钮 -->
        <el-button @click="handleSubmit" type="primary" round style="margin-left: 20px">查询</el-button>
      </div>
    </el-row>

    <!-- 数据展示 -->
    <el-table :data="results" class="lists" @selection-change="handleSelectionChange" border>
      <!-- 选择框 -->
      <el-table-column type="selection" width="55"/>
      <el-table-column prop="maintenanceRecordsId" label="序号" width="60"/>
      <el-table-column prop="fullName" label="用户名" width="80"/>
      <el-table-column prop="repairAddress" label="报修地址" width="150"/>
      <el-table-column prop="repairDetails" label="报修物件" width="150"/>
      <el-table-column prop="maintenanceStatus" label="维修状态" width="100"/>
      <el-table-column prop="repairTime" label="报修时间" width="150"/>
      <el-table-column prop="employeeName" label="维修员" width="150"/>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button class="shanchu" type="danger" @click="deleteUser(scope.row.maintenanceRecordsId)" style="margin-right: 5px;">删除</el-button>
          <el-button class="bianji" plain @click="openEditDialog(scope.row)" style="margin-right: 0;">编辑</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 编辑弹窗 -->
    <el-dialog
        v-model="dialogVisible"
        title="请输入要修改的数据"
        width="500"
        :before-close="handleClose"
    >
      <el-form :model="editForm" ref="editFormRef" label-width="120px">
        <el-form-item label="用户名">
          <el-input v-model="editForm.fullName" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="报修地址">
          <el-input v-model="editForm.repairAddress" placeholder="请输入报修地址" />
        </el-form-item>
        <el-form-item label="报修物件">
          <el-input v-model="editForm.repairDetails" placeholder="请输入报修物件" />
        </el-form-item>
        <el-form-item label="维修状态">
          <el-input v-model="editForm.maintenanceStatus" placeholder="请输入维修状态" />
        </el-form-item>
        <el-form-item label="报修时间">
          <el-date-picker
              v-model="editForm.repairTime"
              type="datetime"
              format="yyyy-MM-dd HH:mm:ss"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="请选择报修时间"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="updateRecord">确认</el-button>
        </div>
      </template>
    </el-dialog>


    <!-- 分页控件 -->
    <div class="example-pagination-block">
      <el-pagination
          layout="prev, pager, next"
          :total="total"
          :page-size="pageSize"
          :current-page="currentPage"
          @current-change="handlePageChange"
      />
    </div>

    <!-- 批量删除按钮 -->
    <div class="batch-delete">
      <el-button type="danger" @click="deleteSelectedUsers">批量删除</el-button>
    </div>

  </div>

</template>

<script setup lang="ts">
import { ref, watch, onMounted } from 'vue';
import axios from 'axios';
import { ElDialog, ElForm, ElFormItem, ElInput, ElDatePicker, ElButton } from 'element-plus';

const type = ref(''); //类型
const repairTime = ref<[Date | null, Date | null]>([null, null]);//时间
const fullName = ref('');//输入框内容
const currentPage = ref(1);//当前页码

// 分页相关状态
const pageNo = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 选项数据
const options = [
  { value: '', label: '类型' },
  { value: '电器', label: '电器' },
  { value: '管道', label: '管道' },
  { value: '木工', label: '木工' },
  { value: '其他', label: '其他' },
];

// 监视这些值的变化  在前端输出
watch([fullName, type, repairTime], () => {
  console.log(`Input: ${fullName.value}, Type: ${type.value}, Date Range: ${repairTime.value}`);
});

// 存储查询结果
const results = ref<Array<any>>([]);

// 表单提交方法
const handleSubmit = () => {
  // 提取日期范围
  const [startTime, endTime] = repairTime.value;
  const formattedStartTime = startTime ? startTime.toISOString() : null;
  const formattedEndTime = endTime ? endTime.toISOString() : null;
  console.log(`输入: ${fullName.value}, 类型: ${type.value}, 开始时间: ${formattedStartTime}, 截止时间: ${formattedEndTime}, 当前页: ${pageNo.value}`);
  axios.post('/api/admin/page10/selectpages', {
    fullName: fullName.value,
    type: type.value,
    startTime: formattedStartTime,
    endTime: formattedEndTime,
    pageNo: pageNo.value,
    pageSize: pageSize.value,
  }).then(response => {
    console.log('API 响应数据:', response.data);
    results.value = response.data.records || [];
    total.value = response.data.total || 0;
  }).catch(error => {
    console.error('Error:', error.response ? error.response.data : error.message);
  });
};

// 在用户选中或取消选中表格中的行时被触发，并将当前选中的行存储在 selectedUsers
const selectedUsers = ref<Array<any>>([]);//存储批量删除选中的信息
const handleSelectionChange = (selection: any) => {  //any 任意类型
  selectedUsers.value = selection;
  console.log(selection)
};

// 批量删除
const deleteSelectedUsers = () => {
  const idsToDelete = selectedUsers.value.map(user => user.maintenanceRecordsId); // 提取选中的 ID，存储到集合中
  axios.delete('/api/admin/page10/deleteusers', {
    headers: {//告诉后端发送的是json文件
      'Content-Type': 'application/json'
    },
    data: idsToDelete // 直接发送 List<Integer>
  }).then(() => {
    results.value = results.value.filter(user => !idsToDelete.includes(user.maintenanceRecordsId));  // 过滤掉已删除的用户
    selectedUsers.value = []; // 清空选中状态
  }).catch(error => {
    console.error('Error:', error.response ? error.response.data : error.message);
  });
};


// 单个删除
const deleteUser = (id) => {
  console.log("传入的ID是:", id); // 添加日志
  axios.delete('/api/admin/page10/deleteuser', {
    data: { mainmaintenanceRecordsId: id }
  }).then(() => {
    results.value = results.value.filter(user => user.maintenanceRecordsId !== id);
  }).catch(error => {
    console.error('Error:', error.response ? error.response.data : error.message);
  });
};


// 存储编辑弹窗状态和数据
const dialogVisible = ref(false);
const editForm = ref({
  fullName: '',
  repairAddress: '',
  repairDetails: '',
  maintenanceStatus: '',
  repairTime: ''
});
// 打开编辑弹窗
const openEditDialog = (row) => {
  console.log('更新的数据是:', row); // 这应该在控制台中显示
  editForm.value = { ...row }; // 复制当前行的数据到编辑表单
  dialogVisible.value = true; // 显示弹窗
};
// 更新记录
const updateRecord = () => {
  // 将日期格式化为字符串
  const formattedRepairTime = editForm.value.repairTime
      ? new Date(editForm.value.repairTime).toISOString().slice(0, 19).replace('T', ' ')
      : null;

  // 创建更新对象，包含格式化后的日期
  const updateData = {
    ...editForm.value,
    repairTime: formattedRepairTime
  };
  axios.put('/api/admin/page10/updaterecord', updateData).then(() => {
    console.log("editForm.value:", updateData);
    // 更新表格数据
    handleSubmit();
    dialogVisible.value = false; // 关闭弹窗
  }).catch(error => {
    console.error('Error:', error.response ? error.response.data : error.message);
  });
};
// 重置编辑表单
const resetForm = () => {
  editForm.value = {
    fullName: '',
    repairAddress: '',
    repairDetails: '',
    maintenanceStatus: '',
    repairTime: ''
  };
};

// 页码改变方法
const handlePageChange = (page: number) => {
  pageNo.value = page;
  currentPage.value = page;
  handleSubmit();
};

//百度地图api ->定位打卡
// 获取当前日期
const currentDate = ref(new Date().getFullYear() + '年' + (new Date().getMonth() + 1) + '月' + new Date().getDate() + '日');
// 存储位置信息
const location = ref<{ province: string, city: string } | null>(null);
// 加载百度地图脚本，目的是初始化BMap
function LoadBaiduMapScript(): Promise<typeof BMap> {  //要先初始化百度地图  定义BMap
  const AK = '1QF2cs9S7wQDdbDoTq56TwjrwcnPG4tS'; //百度地图ak
  const BMap_URL = `https://api.map.baidu.com/api?v=2.0&ak=${AK}&s=1&callback=onBMapCallback`;
  return new Promise((resolve, reject) => {
    if (typeof BMap !== "undefined") {
      resolve(BMap);
      return;
    }
    window.onBMapCallback = function () {
      console.log("百度地图脚本初始化成功...");
      resolve(BMap);
    };
    // 创建 script 元素以加载百度地图脚本
    let scriptNode = document.createElement("script");
    scriptNode.setAttribute("type", "text/javascript");
    scriptNode.setAttribute("src", BMap_URL);
    scriptNode.onerror = () => reject(new Error('百度地图脚本加载失败'));
    document.body.appendChild(scriptNode);
  });
}
const sign = async () => {//如果不使用 async 关键字，你将无法在函数内部使用 await 关键字来暂停函数的执行，
  const storedUsername = localStorage.getItem('adminUsername'); // 获取登录用户名

  try {
    await LoadBaiduMapScript(); // 等待百度地图脚本加载完成
    // 确保 BMap 已经定义
    if (typeof BMap === 'undefined') {
      throw new Error('BMap 未定义');
    }
    // 检查浏览器是否支持地理位置
    if (navigator.geolocation) {    //navigator.geolocation 是一个Web API，它允许网页和应用程序访问设备的地理位置信息
      navigator.geolocation.getCurrentPosition(position => {
        const latitude = position.coords.latitude;// 纬度
        const longitude = position.coords.longitude;// 经度
        // 获取当前时间
        const currentSignTime = new Date().toISOString(); // 这里使用 ISO 8601 格式
        console.log(`当前位置：纬度 ${latitude}, 经度 ${longitude}`);
        console.log(`当前打卡时间：${currentSignTime}`);
        // 使用百度地图 Geocoder 获取详细地址信息
        const geoc = new BMap.Geocoder();
        const point = new BMap.Point(longitude, latitude);//传入经度和纬度
        geoc.getLocation(point, (result) => {
          if (result) {
            const { province, city } = result.addressComponents;// 提取省和城市信息
            location.value = { province, city };
            axios.post('/api/signqjc', {
              username: storedUsername, // 使用更新后的用户信息
              latitude,
              longitude,
              province,
              city,
              signTime: currentSignTime // 传递当前打卡时间
            }).then(response => {
              console.log('打卡成功:', response.data);
            }).catch(error => {
              console.error('打卡失败:', error.response ? error.response.data : error.message);
            });
          }
        });
      }, error => {
        console.error('获取位置失败:', error.message);
      });
    } else {
      console.error('浏览器不支持地理位置');
    }
  } catch (error) {
    console.error('加载百度地图API失败:', error.message);
  }
};

onMounted(() => {
  // 页面加载完成时不立即加载百度地图API，等用户点击打卡按钮时再加载
});

// 调用函数挂载数据
onMounted(() => {
  handleSubmit();
});


</script>
<style scoped>
.title {
  position: absolute;
  top: 75px;
  left: 400px;
  margin-top: 20px;
  margin-left: 10px;
  padding: 10px;
  font-size: 15px;
}
.el-table .cell {
  padding: 8px 0; /* 减少默认 padding */
  margin: 0; /* 确保没有 margin */
  border: none; /* 移除边框 */
}
.selects {
  position: absolute;
  top: 200px;
  left: 460px;
}
.lists {
  position: absolute;
  top: 260px;
  left: 360px;
  width: 77%;
  font-size: 15px;
  background-color: #100e0e;
}
/* 修改表格的行高 */
.el-table .el-table__row {
  height: 40px; /* 调整行高 */
}
.shanchu {
  width: 50px;
}
.example-pagination-block {
  margin-top: 670px;
  display: flex;
  justify-content: center;
}

.lists {
  position: absolute;
  top: 260px;
  left: 360px;
  width: 77%;
  font-size: 15px;
  background-color: transparent; /* 修改背景颜色 */
}


.batch-delete {
  position: absolute;
  top: 200px;
  left: 360px;
}
.shanchu{
  width: 50px;
}
.bianji {
  width: 50px;
  background-color: #409EFF; /* Element Plus 的默认蓝色 */
  border-color: #409EFF; /* 按钮边框颜色 */
  color: #fff; /* 按钮文字颜色 */
}

</style>
